<!--
 * @Descripttion: 科目期初设置
 * @version: V1.0
 * @Author: GW
 * @Date: 2022-04-29 14:24:58
 * @LastEditors: GW
 * @LastEditTime: 2022-06-13 15:44:30
-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="business-big-box" style="margin:2px 8px;">
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :span="2">
                            <div class="btns" @click="handlerSubmit" v-if="permissions.includes('accounting:add')">
                                <a-icon class="btns-icon" type="file-add" />
                                <div class="btns-text">保存</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="syncFun">
                                <a-icon class="btns-icon" type="sync" />
                                <div class="btns-text">刷新</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="trialBalancing">
                                <a-icon class="btns-icon" type="hourglass" />
                                <div class="btns-text">试算平衡</div>
                            </div>
                        </a-col>
                        <!-- <a-col :span="2">
                            <div class="btns" @click="()=>{this.$message.warning('暂未开发')}">
                                <a-icon class="btns-icon" type="import" />
                                <div class="btns-text">导入</div>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <div class="btns" @click="()=>{this.$message.warning('暂未开发')}">
                                <a-icon class="btns-icon" type="setting" />
                                <div class="btns-text">字段设置</div>
                            </div>
                        </a-col> -->
                    </a-col>
                </a-row>
            </div>
            <div class="course-table-container">
                <section style="position:relative">
                    <a-tabs :activeKey="activeKey" @change="onSelectTree">
                        <a-tab-pane v-for="item in treeData[0].children" :key="item.id?item.id:0" :tab="item.title">

                        </a-tab-pane>
                    </a-tabs>
                    <div class="bills-box-header-subjectsini">
                        <div class="filter">
                            <div class="filter-label" style="text-align:right;margin-right:10px;">启用期间: </div>
                            <div class="filter-control" style="line-height:32px">
                                <!-- <a-month-picker placeholder="启用期间" :allowClear="false" v-model="beginDate"></a-month-picker> -->
                                {{beginDate}}
                            </div>
                        </div>
                        <!-- <div class="filter">
                            <div class="filter-label">币种: </div>
                            <div class="filter-control">
                                <a-input @click="searchGroup(1)" @change="searchGroup(2)" v-model="currency" autocomplete="off" placeholder="请选择币种">

                                </a-input>
                                <search-group-header ref="credentialsSearch" :inputValue="currency" :componentName="'currency'" @clickItem="setValue"></search-group-header>
                            </div>
                        </div> -->
                    </div>
                    <div style="height: calc(100vh - 200px);overflow-y: auto;">
                        <a-table id="table_course" :columns="columns" :data-source="data" :rowClassName="rowClassName" bordered :pagination="false" :scroll="{ x: 1000, y: 450}">
                            <div slot="filterDropdownName" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" style="padding: 8px">
                                <a-input :placeholder="`搜索${column.title}`" v-model="searchName" style="width: 188px; margin-bottom: 8px; display: block;" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)" />
                                <a-button type="primary" icon="search" size="small" style="width: 90px; margin-right: 8px" @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
                                    搜索
                                </a-button>
                                <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
                                    重置
                                </a-button>
                            </div>
                            <div slot="filterDropdownCode" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" style="padding: 8px">
                                <a-input :placeholder="`搜索${column.title}`" v-model="searchCode" style="width: 188px; margin-bottom: 8px; display: block;" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)" />
                                <a-button type="primary" icon="search" size="small" style="width: 90px; margin-right: 8px" @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
                                    搜索
                                </a-button>
                                <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
                                    重置
                                </a-button>
                            </div>
                            <a-icon slot="filterIcon" type="filter" theme="filled" :style="{ color: '#444',marginRight:'4px' }" />

                            <div v-for="item in editColumnArraya" :slot="item" slot-scope="text, record ,index" :key="item">
                                <editable-cell v-if="isRouterAlive" :record="record" :col="item" :text="text" :dataSource="data" @showModalAuxiliary="showModalAuxiliary" @change="onCellChange(index, item, $event)" />
                            </div>
                        </a-table>
                    </div>

                </section>
                <!-- <section class="course-tree-box">
                    <a-tree :tree-data="treeData" default-expand-all @select="onSelectTree" show-line>
                        <a-icon slot="switcherIcon" type="down" />
                    </a-tree>
                </section>
                <section class="course-table-box">
                    <a-table id="table_course" :columns="columns" :data-source="data" bordered :row-selection="{selectedRowKeys: selectedKeys, onChange: selection,columnWidth:35}" :pagination="false" :scroll="{ x: 1000, y: 0}">
                        <div slot="filterDropdownName" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" style="padding: 8px">
                            <a-input :placeholder="`搜索${column.title}`" v-model="searchName" style="width: 188px; margin-bottom: 8px; display: block;" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)" />
                            <a-button type="primary" icon="search" size="small" style="width: 90px; margin-right: 8px" @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
                                搜索
                            </a-button>
                            <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
                                重置
                            </a-button>
                        </div>
                        <div slot="filterDropdownCode" slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" style="padding: 8px">
                            <a-input :placeholder="`搜索${column.title}`" v-model="searchCode" style="width: 188px; margin-bottom: 8px; display: block;" @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])" @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)" />
                            <a-button type="primary" icon="search" size="small" style="width: 90px; margin-right: 8px" @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)">
                                搜索
                            </a-button>
                            <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
                                重置
                            </a-button>
                        </div>
                        <a-icon slot="filterIcon" type="filter" theme="filled" :style="{ color: '#444',marginRight:'4px' }" />
                    </a-table>
                </section> -->
            </div>
        </div>
        <!--试算平衡-->
        <drag-modal title="期初试算平衡" :visible="trialVisible" @cancel="closeTrialVisible" :width="600">
            <div v-if="trialClass != null" class="balance-wrapper" :class="trialClass">
                <div class="balance-left">
                    {{beginDebitAmount | NumFormat}}
                </div>
                <div class="balance-right">
                    {{beginCreditAmount | NumFormat}}
                </div>
                <div class="balance-center"></div>
                <div class="balance-down"></div>
                <div class="jie-text">
                    借
                </div>
                <div class="dai-text">
                    贷
                </div>
            </div>
            <div v-else class="balance-load">
                <a-spin tip="试算平衡中..." size="large">

                </a-spin>
            </div>
        </drag-modal>
    </div>
</template>
<script>

import { mapState } from "vuex";
import table from "@/mixins/table";
import { deleteAccount, getAccount, pageRun } from "@/api/erp/accounting";
import { getNowAccount } from '@/api/finance/accountingSearch';
import { save, getList, trialBalance } from '@/api/finance/subjectsBalance';

import { list } from "@/api/erp/currency";
import { unitList } from "@/api/inventory/unit";
import { getDetail } from "@/api/erp/erpGradeRule";
import { cardWrapper } from "@/components/CardWrapper";
import { Controlwidth } from "@/utils/antTableComponents";
import editableCell from "../accounting/editTable/EditableCell";
import searchGroupHeader from "@/components/Finance/searchGroupHeader";
import { number2Format } from "@/utils/tool/number-formart";
let keyMap = new Map();

export default {
    mixins: [table],
    components: {
        cardWrapper,
        editableCell,
        searchGroupHeader
    },
    updated () {
        Controlwidth("table_course", 50);
    },
    data () {
        const parentColumns = [
            {
                title: "级次",
                dataIndex: "accountingDepth",
                key: "officeName",
                align: "left",
                width: 50
            },
            {
                title: "科目名称",
                dataIndex: "accountingName",
                key: "officeName",
                align: "left",
                width: 100
            },
            {
                title: "科目编码",
                dataIndex: "accountingCode",
                key: "officeName",
                align: "left",
                width: 100,
            },
        ];

        const columns = [
            {
                title: "序号",
                dataIndex: "index",
                key: "index",
                align: "center",
                width: 20,
                customRender: (text, row, index) => {
                    return index + 1;
                }
            },
            {
                title: "级次",
                dataIndex: "accountingDepth",
                key: "depth",
                align: "center",
                width: 40,
            },
            {
                title: "科目编码",
                dataIndex: "accountingCode",
                key: "code",
                align: "left",
                width: 100,
                scopedSlots: {
                    filterDropdown: 'filterDropdownCode',
                    filterIcon: 'filterIcon',
                },
                customRender: (text, row, index) => {
                    if (row.accountingDepth != 1) {
                        let lelft = 10 * row.accountingDepth + "px";
                        let style = { marginLeft: lelft };
                        return <span style={style} >{text}</span>;
                    } else {
                        return <span>{text}</span>;
                    }
                }
            },
            {
                title: "科目名称",
                dataIndex: "accountingName",
                key: "name",
                align: "left",
                width: 100,
                scopedSlots: {
                    filterDropdown: 'filterDropdownName',
                    filterIcon: 'filterIcon',
                },
                customRender: (text, row, index) => {
                    if (row.accountingDepth != 1) {
                        let lelft = 10 * row.accountingDepth + "px";
                        let style = { marginLeft: lelft };
                        return <span style={style} >{text}</span>;
                    } else {
                        return <span>{text}</span>;
                    }
                }
            },
            {
                title: "科目类型",
                width: 60,
                dataIndex: "accountingTypeName",
                key: "accountingTypeName",
                align: "center",
            },
            {
                title: "辅助核算项",
                dataIndex: "officeName",
                key: "officeName",
                align: "left",
                width: 100,
                ellipsis: true,
                customRender: (text, row, index) => {
                    if (row.isEndNode) {
                        let content = [];
                        if (row.isAuxaccDepartment) {
                            content.push("部门核算");
                        }
                        if (row.isAuxaccPerson) {
                            content.push("人个往来");
                        }
                        if (row.isAuxaccCustomer) {
                            content.push("客户往来");
                        }
                        if (row.isAuxaccSupplier) {
                            content.push("供应商往来");
                        }
                        if (row.isAuxaccProject) {
                            content.push("项目核算");
                        }
                        if (row.isAuxaccInventory) {
                            content.push("物料");
                        }
                        return content.join('，');
                    } else {
                        return '';
                    }
                }
            },
            {
                title: "方向",
                width: 60,
                dataIndex: "beginAmountDirection",
                key: "beginAmountDirection",
                align: "center",
                scopedSlots: { customRender: 'beginAmountDirection' },
                // customRender: (text, row, index) => {
                //     if (text) {
                //         return text == 1 ? "借方" : "贷方";
                //     }
                // }
            },
            {
                title: "期初余额",
                dataIndex: "endAmount",
                key: "endAmount",
                align: "left",
                width: 80,
                scopedSlots: { customRender: 'endAmount' },
            },
            {
                title: "本年累计借方金额",
                dataIndex: "debitAmount",
                key: "debitAmount",
                align: "left",
                width: 80,
                scopedSlots: { customRender: 'debitAmount' },
            },
            {
                title: "本年累积贷方金额",
                dataIndex: "creditAmount",
                key: "creditAmount",
                align: "left",
                width: 80,
                scopedSlots: { customRender: 'creditAmount' },
            },
            {
                title: "年初余额",
                dataIndex: "beginAmount",
                key: "beginAmount",
                align: "left",
                width: 80,
                customRender: (text) => {
                    return <div style="width:100%;text-align:right">{number2Format(text)}</div>;
                }
            }

        ];

        return {
            selectedKeys: [],
            parentSelectedKeys: [],
            selectedData: {},
            parentSelectedData: {},
            selectedIds: [],
            columns,
            parentColumns,
            data: [],
            editModal: false,
            parentModal: false,
            cashAccountCheck: [],
            accountingTypeName: '',//科目类型名称
            type: 1,
            currentId: null,//当前条id
            pagination: {
                size: "small",
                defaultPageSize: -1,
                current: 1,
                pageSize: -1,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.pagination.pageSize}
                                min={1}
                                max={10}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    this.pagination.current = page;
                    this.PageList();
                },
            },
            editItem: {
                accountingTypeId: "", //科目类型
                bookFormat: 1, //账页格式
                dcDirection: 1, //余额方向
                type: "",
                parentId: null, //上级id
                parentName: "", //上级名称
                isBillingInfo: null,
                isBank: null,//银行科目
                isCash: null,//现金科目
                isCashEquivalents: null,//现金等价物科目
                isDayBook: null,//日记账
                defaultCurrencyId: null,
                defaultCurrencyName: null,
                unitId: null,
                unitName: null,
            },
            currencyData: [],
            currency: null,
            ruleCode: "",
            postData: { accountingTypeId: "" },
            searchName: null,
            searchCode: null,
            treeData: [{
                title: '科目分类',
                key: '',
                children: [],
            }],
            editColumnArraya: [],
            isRouterAlive: true,
            activeKey: 0,

            beginDate: null,
            trialVisible: false,
            beginCreditAmount: null,//贷
            beginDebitAmount: null,//借
            trialClass: null
        }
    },
    activated () {
        this.getCurrencyList();
        this.getUnitList();
    },
    created () {
        this.PageList();
        this.editColumnArray(this.columns);
        this.getAccount();//获取科目分类

        this.getNowAccount();
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),

    },
    methods: {
        getNowAccount () {
            //获取当前账套
            getNowAccount().then(res => {
                if (res.code === 200) {
                    console.log(res);
                    let monthArray = [];
                    let accountBeginDate = res.data.beginDate;
                    let accountEndDate = res.data.endDate;

                    let accountMonthBegin = accountBeginDate.split('-');
                    let accountMonthEnd = accountEndDate.split('-');

                    let year = accountMonthBegin[0];
                    let month = parseInt(accountMonthBegin[1]);

                    let monthEnd = accountMonthEnd[1];
                    console.log(year, month, monthEnd);

                    for (let i = month; i <= monthEnd; i++) {
                        let m = year + '-' + (i < 10 ? '0' + i : i);
                        monthArray.push(m);
                    }
                    this.beginDate = res.data.beginDate;

                }
            })
        },
        reload () {
            //强制刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },
        rowClassName (record, index) {
            return !record.isEndNode ? 'disabledClass' : '';
        },
        //获取可编辑的列名
        editColumnArray (column) {
            let editcloumn = [];
            column.forEach((item, index) => {
                editcloumn.push(item.dataIndex);
            });
            this.editColumnArraya = editcloumn;
            console.log(this.editColumnArraya)
        },
        //获取科目分类
        getAccount () {
            getAccount().then(res => {
                if (res.code === 200) {

                    let data = res.data.map(v => {
                        return { ...v, isLeaf: true, title: v.name, key: v.id }
                    })
                    this.treeData[0].children = data;

                    this.treeData[0].children.unshift({ id: null, title: '全部' })
                    console.log(data)
                }
            })
        },
        // 获取列表
        PageList () {
            const { postData } = this;
            postData.current = this.pagination.current;
            postData.size = this.pagination.pageSize;
            if (this.searchCode) {
                postData.code = this.searchCode;
                postData.name = null;
            } else if (this.searchName) {
                postData.name = this.searchName;
                postData.code = null;
            } else {
                postData.name = null;
                postData.code = null;
            }
            getList(postData).then(response => {
                if (response.code === 200) {
                    const { data } = response;

                    this.data = data.map(v => {
                        return { ...v, key: v.accountingId }
                    });

                    console.log(this.data)
                    this.reload();
                }
            }).catch(error => { });
        },
        handlerChangeCurrency (key, val) {
            console.log(key, val)
            this.editItem.defaultCurrencyName = val.componentOptions.children[0].text;
        },
        handlerChangeUnit (key, val) {
            console.log(key, val);
            this.editItem.unitName = val.componentOptions.children[0].text;
        },
        //树形菜单
        onSelectTree (keys) {
            console.log(keys)
            this.activeKey = keys ? keys : 0;
            this.postData.accountingTypeId = keys == 0 ? null : keys;
            this.PageList();
        },
        //获取外币
        getCurrencyList () {
            list({ isBaseCurrency: false }).then(res => {
                this.currencyData = res.data;
            });
        },
        //获取计量单位
        getUnitList () {
            unitList().then(res => {
                this.unitData = res.data;
            });
        },
        handleChange (key, value) {
            console.log(key, value);
            this.accountingTypeName = value.componentOptions.children[0].text;
        },
        auxiliaryCheck () {
            // <a-checkbox v-model="editItem.isAuxaccDepartment" :disabled="auxiliaryA" @change="auxiliaryCheck('a')">部门核算</a-checkbox>
            // <a-checkbox v-model="editItem.isAuxaccPerson" :disabled="auxiliaryB" @change="auxiliaryCheck('b')">个人往来</a-checkbox>
            // <a-checkbox v-model="editItem.isAuxaccCustomer" :disabled="auxiliaryC" @change="auxiliaryCheck('c')">客户往来</a-checkbox>
            // <a-checkbox v-model="editItem.isAuxaccSupplier" :disabled="auxiliaryD" @change="auxiliaryCheck('d')">供应商往来</a-checkbox>
            if (this.editItem.isAuxaccPerson) {
                //个人往来
                this.editItem.isAuxaccDepartment = false;
                this.editItem.isAuxaccCustomer = false;
                this.editItem.isAuxaccSupplier = false;
                this.auxiliaryA = true;
                this.auxiliaryC = true;
                this.auxiliaryD = true;
            } else {
                this.auxiliaryA = false;
                this.auxiliaryC = false;
                this.auxiliaryD = false;

                if (this.editItem.isAuxaccSupplier) {
                    //供应商往来
                    this.auxiliaryB = true;
                    this.auxiliaryC = true;
                    this.editItem.isAuxaccPerson = false;
                    this.editItem.isAuxaccCustomer = false;
                } else {
                    this.auxiliaryB = false;
                    this.auxiliaryC = false;

                    if (this.editItem.isAuxaccCustomer) {
                        //客户往来
                        this.auxiliaryB = true;
                        this.auxiliaryD = true;
                        this.editItem.isAuxaccPerson = false;
                        this.editItem.isAuxaccSupplier = false;
                    } else {
                        this.auxiliaryB = false;
                        this.auxiliaryD = false;
                    }
                }
                if (this.editItem.isAuxaccDepartment) {
                    //部门核算
                    this.auxiliaryB = true;
                    this.editItem.isAuxaccPerson = false;
                }
            }

            if (this.editItem.isAuxaccPerson && this.editItem.isAuxaccProject) {
                //个人往来，项目核算
                this.auxiliaryC = true;
                this.auxiliaryD = true;

                this.editItem.isAuxaccCustomer = false;
                this.editItem.isAuxaccSupplier = false;
            }
        },
        //table check选择
        selection (keys, row) {
            this.selectedKeys = [];
            this.selectedKeys = keys;
            this.selectedData = row[0];
            const ids = new Array();
            row.forEach(function (val) {
                ids.push(val.id);
            });
            this.selectedIds = ids;
            console.log("rowKeys", this.selectedData, keys);
        },
        syncFun () {
            //刷新
            this.PageList();
        },
        //上级table选择
        parentSelection (keys, row) {
            console.log(row)
            this.parentSelectedKeys = [];
            this.parentSelectedKeys = keys;
            this.parentSelectedData = row[0];
        },
        selectParentData () {
            if (this.parentSelectedKeys.length != 1) {
                this.$message.error("只能选择一条数据");
                return;
            }
            this.editItem.parentId = this.parentSelectedData.id;
            this.editItem.parentName = this.parentSelectedData.name;


            // this.form.setFieldsValue({ code: this.parentSelectedData.code });
            this.editItem.depth = this.parentSelectedData.depth + 1;

            // this.editItem.accountingTypeId = this.parentSelectedData.accountingTypeId;
            console.log(this.parentSelectedData);
            // return;
            this.accountingTypeName = this.parentSelectedData.accountingTypeName;

            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        accountingTypeId: this.$form.createFormField({
                            value: this.parentSelectedData.accountingTypeId
                        }),
                        code: this.$form.createFormField({
                            value: this.parentSelectedData.code
                        }),
                    };
                }
            });


            this.parentModal = false;
        },
        setValue (data) {
            this.currency = data.name;
        },
        //获取编码规则
        getCodeDetail () {
            getDetail({ code: 'code' }).then(res => {
                if (res.code == 200) {
                    let code = res.data.codingRule;
                    console.log("code", code);
                    // for (let i = 0; i < code.length; i++) {
                    //     this.ruleCode += code.substring(i, i + 1);
                    //     if (i + 1 < code.length) {
                    //         this.ruleCode += "-";
                    //     }
                    // }
                    this.ruleCode = this.codeStyle(code);
                }
            });
        },
        //处理编码规则样式
        codeStyle (code) {
            let codeText = "";
            for (let i = 0; i < code.length; i++) {
                let codeNum = code.substring(i, i + 1);
                for (let index = 0; index < codeNum; index++) {
                    codeText += "*";
                }
                codeText += " ";
            }
            return codeText;
        },
        //改变分页大小
        changePageSize (e) {
            const value = e.target.value;
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            Object.assign(this.pagination, {
                current: 1,
                pageSize: size,
            });

            this.PageList();
        },
        handleSearch (key, confirm, col) {
            //table搜索
            confirm();
            console.log(key, confirm, col)
            if (col == 'accountingName') {
                this.searchName = key[0];
                this.searchCode = null;
            } else {
                this.searchCode = key[0];
                this.searchName = null;
            }
            this.PageList()
        },
        handleReset (clearFilters) {
            clearFilters();
            this.searchCode = '';
            this.searchName = '';
            this.PageList()
        },
        showModalAuxiliary () {
            console.log('进入了---------修改的弹窗');
            this.dataSource.forEach((item, index) => {
                if (index == this.currentIndexTable) {
                    console.log('当前行数据：', item);

                    this.isQuantity = item.quantityBegin || item.quantityBegin == 0 ? true : false;   //是否数量核算
                    this.isExchange = item.currencyBeginAmount || item.currencyBeginAmount == 0 ? true : false;//是否外币核算


                    console.log(this.isBank, this.isAuxaccCustomer, this.isAuxaccDepartment, this.isAuxaccPerson, this.isAuxaccProject, this.isAuxaccSupplier)

                    if (this.isBank || this.isAuxaccCustomer || this.isAuxaccDepartment || this.isAuxaccPerson || this.isAuxaccProject || this.isAuxaccSupplier || this.isQuantity || this.isExchange) {
                        this.auxiliaryModal = true;
                    }


                    this.currencyBeginAmount = item.currencyBeginAmount;   //原币金额
                    this.currencyId = item.currencyId;       //币种id
                    this.currencyName = item.currencyName;    //币种名称
                    this.exchangeRate = item.exchangeRate;    //汇率
                    this.debitAmountType = item.debitAmount > 0 ? 1 : 2;     //借贷方向
                    this.quantityBegin = item.quantityBegin;        //数量
                    this.price = item.price;           //单价
                    this.unitId = item.unitId;          //计量单位id
                    this.unitName = item.unitName;        //计量单位名称
                }
            });

            //获取币种详情（折算方式和汇率）
            // if (this.currencyId) {
            //     this.getCurrencyDetailId(this.currencyId);
            // }
        },
        searchGroup (t) {
            if (t == 1) {
                this.$refs.credentialsSearch.showModal();
            } else {
                //延迟请求
                if (this.setTime) {
                    clearTimeout(this.setTime)
                }
                this.setTime = setTimeout(() => {
                    this.$refs.credentialsSearch.inputSearch();
                }, 500)
            }
        },
        onChangePicker (e, v) {
            console.log(e, v)
            this.beginDate = moment(v).format('MM');
        },
        handlerSubmit () {
            //提交数据
            // this.dataJson = this.dataSource.filter(e => { return e.accountingId });//表明细
            // if (this.dataJson.length < 1) {
            //     this.$message.warning('请输入明细表');
            //     return;
            // }


            // //判断辅助项
            // let vdetails = this.dataJson;

            // for (let i = 0; i < vdetails.length; i++) {
            //     let item = vdetails[i];

            //     if (item.officeId == 0 || item.projectId == 0 || item.settleId == 0 || item.vendorId == 0 || item.userId == 0 || item.crmId == 0) {
            //         if (item.auxiliaryItem == '' || !item.auxiliaryItem || item.auxiliaryItem == null) {
            //             this.$message.warning(`第${i + 1}行: 辅助项必须填写完整!`);
            //             return;
            //         }
            //     }
            // }
            let requestData = JSON.parse(JSON.stringify(this.data));

            if (this.currentId) {
                requestData.id = this.currentId;
            }
            requestData.forEach(item => {
                //启用期间
                item.accountPeriod = Number(this.beginDate);
            })
            console.log('提交的数据：', requestData, this.beginDate);
            // return;
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.editMask = true;
                    this.voucherState = 0;

                    let that = this;
                    let success = `成功条数：${response.data.sCount}`;
                    let error = `失败条数：${response.data.fCount}`;
                    let msg = [];
                    for (let i = 0; i < response.data.result.length; i++) {
                        msg.push(<div>{response.data.result[i]}</div>);
                    }
                    let content = <div>
                        <span style="font-size:16px;color:green">{success}</span><br />
                        <span style="font-size:16px;color:red">{error}</span><br />
                        <div style="max-height:180px;overflow-y:auto;">{msg}</div>
                    </div>;
                    this.$confirm({
                        icon: () => { return <a-icon type="exclamation-circle" /> },
                        title: '操作结果',
                        content: content,
                        okText: '确定',
                        cancelText: '关闭',
                        footer: null,
                        onOk () {
                            that.PageList();
                        },
                        onCancel () {
                            that.PageList();
                        },
                    });
                } else {
                    this.$message.warning(res.message);
                }
            }).catch(error => {

            })
        },
        onCellChange (indexTable, dataIndex, value) {
            console.log('进入了---------第一次选择科目时的弹窗');
            //当前点击的行下标
            this.currentIndexTable = indexTable;
            console.log('当前点击的数据：', value);

            const dataSource = [...this.data];
            const target = dataSource.find((item, index) => index === indexTable);
            if (dataIndex == 'accountingName') {
                if (value) {
                    target['accountingName'] = value.treeNames.split('/').join('-');
                    target['accountingId'] = value.id;
                    target['accountingCode'] = value.code;

                    value.isAuxaccCustomer ? target['crmId'] = 0 : target['crmId'] = null;//客户
                    value.isAuxaccDepartment ? target['officeId'] = 0 : target['officeId'] = null;//部门
                    value.isAuxaccPerson ? target['userId'] = 0 : target['userId'] = null;//个人
                    value.isAuxaccProject ? target['projectId'] = 0 : target['projectId'] = null;//项目
                    value.isAuxaccSupplier ? target['vendorId'] = 0 : target['vendorId'] = null;//供应商
                    value.isBank || value.isCash || value.isCashEquivalents ? target['settleId'] = 0 : target['settleId'] = null;//现金银行
                    value.isQuantity ? target['unitId'] = value.unitId : target['unitId'] = null;   //是否数量核算
                    value.isExchange ? target['currencyId'] = value.defaultCurrencyId : target['currencyId'] = null;//是否外币核算

                    target['unitId'] = value.unitId;            //计量单位id
                    target['unitName'] = value.unitName;        //计量单位名称
                    target['currencyId'] = value.defaultCurrencyId;            //币种id
                    target['currencyName'] = value.defaultCurrencyName;        //币种名称
                } else {
                    target['accountingName'] = null;
                    target['accountingId'] = null;
                }

            } else if (dataIndex == 'debitAmount') {
                //借方金额
                target[dataIndex] = value;
            } else if (dataIndex == 'creditAmount') {
                //贷方金额
                target[dataIndex] = value;
            } else if (dataIndex == 'endAmount') {
                if (target.isAuxaccCustomer || target.isAuxaccDepartment || target.isAuxaccPerson || target.isAuxaccProject || target.isAuxaccSupplier) {
                    target['endAmount'] = value.value;
                    target['beginAmountDirection'] = value.beginAmountDirection;
                } else {
                    target[dataIndex] = value;
                }
            } else if (dataIndex == 'beginAmountDirection') {
                target['beginAmountDirection'] = value;

                if (value == 1) {
                    //借方  年初余额 = 期初余额 - 累计借方金额 + 累计贷方金额 
                    target['beginAmount'] = Number(target.endAmount) - Number(target.debitAmount) + Number(target.creditAmount)
                }
                if (value == 2) {
                    //贷方 年初余额 = 期初余额  + 累计借方金额 - 累计贷方金额
                    target['beginAmount'] = Number(target.endAmount) + Number(target.debitAmount) - Number(target.creditAmount)
                }


            } else {
                target[dataIndex] = value;
            }

            if (target.endAmount != null && target.endAmount != 0) {
                if (target.beginAmountDirection == 1) {
                    //借方  年初余额 = 期初余额 - 累计借方金额 + 累计贷方金额 
                    target['beginAmount'] = Number(target.endAmount) - Number(target.debitAmount) + Number(target.creditAmount)
                }
                if (target.beginAmountDirection == 2) {
                    //贷方 年初余额 = 期初余额  + 累计借方金额 - 累计贷方金额
                    target['beginAmount'] = Number(target.endAmount) + Number(target.debitAmount) - Number(target.creditAmount)
                }
            }

            this.$nextTick(() => {
                //科目期初金额累加操作
                let parentMax = dataSource.filter(item => item.accountingParentId == 0);//顶级父级
                let parent = dataSource.filter(item => item.accountingParentId != 0);//次级父级
                let child = dataSource.filter(item => item.accountingParentId != 0 && item.isEndNode);//子级

                parent.forEach(p => {
                    if (!p.isEndNode) {
                        p.endAmount = null;
                    }
                    child.forEach(c => {
                        if (p.accountingId == c.accountingParentId) {
                            if (c.beginAmountDirection == 1) {
                                //借
                                p.endAmount -= Number(c.endAmount);
                            }
                            if (c.beginAmountDirection == 2) {
                                //贷
                                p.endAmount += Number(c.endAmount);
                            }
                        }
                    });

                    // p.endAmount = Number(jie) - Number(dai);
                    if (!p.isEndNode) {
                        if (p.endAmount > 0) {
                            p.beginAmountDirection = 2;//>0 贷
                        }

                        if (p.endAmount < 0) {
                            p.beginAmountDirection = 1;//<0 借
                        }
                    }
                    if (p.endAmount) {
                        p.endAmount = Math.abs(p.endAmount);
                    } else {
                        p.endAmount = null;
                    }
                });

                parentMax.forEach(m => {
                    if (!m.isEndNode) {
                        m.endAmount = null;
                    }
                    parent.forEach(p => {
                        if (m.accountingId == p.accountingParentId) {
                            if (p.beginAmountDirection == 1) {
                                //借
                                m.endAmount -= Number(p.endAmount);
                            }
                            if (p.beginAmountDirection == 2) {
                                //贷
                                m.endAmount += Number(p.endAmount);
                            }
                        }
                    });

                    if (!m.isEndNode) {
                        if (m.endAmount > 0) {
                            m.beginAmountDirection = 2;//>0 贷
                        }
                        if (m.endAmount < 0) {
                            m.beginAmountDirection = 1;//<0 借
                        }
                    }

                    if (m.endAmount) {
                        m.endAmount = Math.abs(m.endAmount);
                    } else {
                        m.endAmount = null;
                    }

                });

                console.log('parent', parent);
                this.data = dataSource;
                this.reload();
            })


        },
        trialBalancing () {
            this.trialVisible = true;
            setTimeout(() => {
                trialBalance().then(res => {
                    if (res.code === 200) {
                        this.beginCreditAmount = res.data.beginCreditAmount;
                        this.beginDebitAmount = res.data.beginDebitAmount;
                        setTimeout(() => {
                            this.trialClass = this.beginDebitAmount > this.beginCreditAmount ? 'left-active' : this.beginDebitAmount < this.beginCreditAmount ? 'right-active' : ''
                        }, 400)
                    }
                })
            }, 1600)
        },
        closeTrialVisible () {
            this.trialVisible = false;
            setTimeout(() => {
                this.trialClass = '';
                this.beginCreditAmount = 0;
                this.beginDebitAmount = 0;
            }, 500)
        }
    }
};
</script>
<style  scoped>
    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
        margin-bottom: 0px !important;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }

    .ant-checkbox-wrapper + .ant-checkbox-wrapper {
        margin-left: 0px;
    }
    .ant-checkbox-wrapper {
        margin-top: 10px;
    }
    .ant-radio-wrapper {
        margin-top: 10px;
    }
</style>
<style lang="less">
    @import '~@/style/setting/business.less';
    .course-table-container {
        // display: flex;
        width: 1200px;
        height: calc(100% - 45px);
        border-bottom: none;
        margin: 0px 10px 0 10px;
        .course-tree-box {
            flex: 0 0 250px;
            height: 100%;
            overflow-y: auto;
            background: #fff;
        }
        .course-table-box {
            width: calc(100% - 250px);
            flex: 1;
            font-size: 12px;
            padding: 10px;
            border-left: 1px solid #ccc;
            overflow-y: auto;
            .ant-pagination {
                padding-left: 20px;
            }
        }
    }
    .course-ant-modal-body {
        .ant-modal-body {
            padding: 0px;
        }
    }
    .tabs-course-box {
        position: relative;
    }
    .disabledClass {
        background: #eee;
    }

    .bills-box-header-subjectsini {
        position: absolute;
        font-size: 14px;
        right: 0px;
        top: 0;
        display: flex;

        .ant-select-selection,
        .ant-input,
        .ant-input-number {
            border: none;
        }
        .ant-input {
            height: 30px;
            text-align: left;
            font-size: 13px;
            padding: 0;
            border-radius: 0;
            border: 1px solid #ddd !important;
        }
        .ant-select-selection--single {
            height: 28px !important;
        }
        .ant-select-selection {
            border: 1px solid #ddd !important;
            border-radius: 0;
        }
        // justify-content: space-around;
        .filter {
            display: table;
            width: 246px;
            margin-bottom: 5px;
            .filter-label {
                display: table-cell;
                font-weight: normal;
                max-width: 160px;
                line-height: 32px;
                white-space: nowrap;
                vertical-align: bottom;
                text-overflow: ellipsis;
                overflow: hidden;
            }
            .filter-control {
                display: table-cell;
                margin-left: 10%;
            }
        }
    }

    .balance-wrapper {
        position: relative;
        width: 500px;
        height: 200px;
        margin: 0 auto;
        .balance-left {
            display: inline-block;
            white-space: nowrap;
            position: absolute;
            border-radius: 20px;
            font-size: 12px;
            text-align: center;
            left: 134px;
            bottom: 58px;
            width: 73px;
            height: 39px;
            background: url('../../../assets/balance.png') #ffffff no-repeat;
            background-position: 1px 21px;
            z-index: 3;
            transition: all 0.4s;
        }
        .balance-right {
            display: inline-block;
            white-space: nowrap;
            position: absolute;
            border-radius: 20px;
            font-size: 12px;
            text-align: center;
            right: 133px;
            bottom: 58px;
            width: 73px;
            height: 39px;
            background: url('../../../assets/balance.png') #ffffff no-repeat;
            background-position: -158px 21px;
            z-index: 3;
            transition: all 0.4s;
        }
        .balance-center {
            position: absolute;
            left: 163px;
            bottom: 44px;
            width: 172px;
            height: 18px;
            background: url('../../../assets/balance.png') #ffffff no-repeat;
            background-position: -28px -14px;
            transition: all 0.4s;
        }
        .balance-down {
            position: absolute;
            left: 50%;
            bottom: 0;
            margin-left: -150px;
            width: 300px;
            height: 47px;
            background: url('../../../assets/balance.png') no-repeat;
            background-position: bottom;
        }
        .jie-text {
            position: absolute;
            left: 160px;
            top: 50px;
        }
        .dai-text {
            position: absolute;
            right: 160px;
            top: 50px;
        }
        &.left-active {
            transition: all 0.2s;
            .balance-left {
                bottom: 51px;
                transition: all 0.4s;
            }
            .balance-right {
                bottom: 65px;
                transition: all 0.4s;
            }
            .balance-center {
                transform: rotate(-5deg);
                transition: all 0.4s;
            }
        }
        &.right-active {
            .balance-left {
                bottom: 65px;
                transition: all 0.4s;
            }
            .balance-right {
                bottom: 51px;
                transition: all 0.4s;
            }
            .balance-center {
                transform: rotate(5deg);
                transition: all 0.4s;
            }
        }
    }
    .balance-load {
        text-align: center;
        width: 500px;
        height: 200px;
        padding-top: 80px;
        box-sizing: border-box;
    }
</style>
 
